package com.xing.controller;




import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.common.dto.BrowseDto;
import com.xing.common.lang.Result;
import com.xing.model.Blog;
import com.xing.service.BlogService;
import com.xing.util.IPUtils;
import com.xing.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 *  博客文章控制器
 * </p>
 *
 * @author 柠檬有点甜
 * @since 2021-08-17
 */
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "currentPage") Integer currentPage){

        if (currentPage== null ||currentPage<1) currentPage = 1;
        Page page = new Page(currentPage, 5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return  Result.succ(pageData);
    }

    @GetMapping("/ShowBrowseCount")
    public  Result ShowBrowseCount(){
        return blogService.ShowBrowseCount();
    }


    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除");
        return Result.succ(blog);
    }


    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {

        Blog temp = null;
        if(blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            // 只能编辑自己的文章
            System.out.println(ShiroUtil.getProfile().getId());
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtil.getProfile().getId().longValue(), "没有权限编辑");

        } else {
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);

        return Result.succ(null);
    }

    /*
    * 添加浏览记录
    * 设计的是 每隔5分钟同一ip，查看一次增加一条数据
    */
    @GetMapping("/blog/addbrowseCount")
    public void addbrowseCount(HttpServletRequest request,int blogId){
        /*获取客户端的ip地址*/
        String ip = IPUtils.getIpAddr(request);
        blogService.saveBrowseRedis(ip,String.valueOf(blogId));
    }

    /*
    * 浏览记录保存数据库
    * */
    @Scheduled(cron = "0 0/30 * * * ?")//每隔半小时执行一次
    public void  detectDeviceStatus(){
//        System.out.println("更新浏览数量");
        List<BrowseDto> browseCountFromRedis = blogService.getBrowseCountFromRedis();
        if (CollectionUtils.isNotEmpty(browseCountFromRedis)){//不为空才更新
//            System.out.println("redis内容清空,接下来保存数据库");
            blogService.addBrowseCount(browseCountFromRedis); //批量更新
        }
    }

    /*更新最热排行数据*/
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点更新
    @GetMapping("/saveHotTop")
    public void saveHotTop(){
        blogService.saveHotTop();
    }
}

